<template>
  <!-- 正常维护工单，试验工单 , 计划检修-->
  <div class="normalDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :moreBtnArr="moreBtnArr"
      :showMore="showMore"
      showStep
      showTopTitle
      :creatInfo="formData"
      :closeBox="closeCheckRecord"
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        {{ topTitlename }} {{ formData.code }}
      </template>
      <div class="orderTitle">
        <div class="tipText">
          标题自动生成规则：{设备管理单位名称}{工作内容}
        </div>
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span class="titleText" :title="orderTitle">{{ orderTitle }}</span>
          <el-link
            v-show="!baseAttachBtn"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <el-input
            type="text"
            v-model="orderTitle"
            @blur="loseFocus"
            @change="userInputTitle"
            placeholder="请输入名称"
            clearable
            ref="mark"
          >
            <template slot="prepend">标题</template>
          </el-input>
        </div>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">基本信息</template>
          <detailForm
            ref="basicForm"
            :initData="formData"
            :orderStatus="status"
            :pageType="pageType"
            :menuType="menuType"
            @changeFormData="changeFormData"
            @setNeedStatus="setNeedStatus"
            @initUserInput="initUserInput"
            @setOrderTitle="setOrderTitle"
            @setDeptIds="setDeptIds"
          ></detailForm>
        </el-collapse-item>
        <el-collapse-item name="2" v-if="showWorkList">
          <template slot="title">作业表单</template>
          <workList
            :currentDept="currentDept"
            ref="workList"
            :formData="formData"
            :orderType="menuType"
            :pageType="pageType"
            :disabled="baseAttachBtn"
            :deptIds="deptIds"
          ></workList>
        </el-collapse-item>
        <el-collapse-item name="3" v-if="showDispatch">
          <template slot="title">派工信息</template>
          <dispatch
            ref="dispatch"
            :formData="formData"
            :orderType="menuType"
            :pageType="pageType"
            @changeData="changeData"
            @setDispatchTime="setDispatchTime"
          />
        </el-collapse-item>
        <div v-if="showWorkTicket && haveTicketData">
          <el-collapse-item name="4">
            <template slot="title">工作票信息</template>
            <wokTicketList
              :orderId="formData.id"
              @haveData="(val) => (haveTicketData = val)"
            ></wokTicketList>
          </el-collapse-item>
        </div>
        <div v-if="showWorkTicket && haveServiceData">
          <el-collapse-item name="5">
            <template slot="title">检修申请信息</template>
            <serviceList
              :orderId="formData.code"
              @haveData="(val) => (haveServiceData = val)"
            ></serviceList>
          </el-collapse-item>
        </div>

        <el-collapse-item name="6" v-if="showWorkListNext">
          <template slot="title">作业表单</template>
          <workListExecute
            v-if="showWorkListNext"
            :currentDept="currentDept"
            ref="workListExecute"
            :formData="formData"
            :orderType="menuType"
            :pageType="pageType"
            :isEdit="editWorkList"
          ></workListExecute>
        </el-collapse-item>

        <el-collapse-item name="7" v-if="showPerform">
          <template slot="title">执行信息</template>
          <addPerformItem
            ref="perform"
            :hideBtn="hidePerformBtn"
            :formData="formData"
            :orderId="formData.id"
            :orderStatus="status"
            :orderType="menuType"
            :pageType="pageType"
            :btnJurisdiction="btnJurisdiction"
            @changePerformData="(val) => (havaPerformData = val)"
          ></addPerformItem>
        </el-collapse-item>
        <el-collapse-item name="8" v-if="showReport">
          <template slot="title">试验报告</template>

          <div class="reportDiv">
            <template v-for="(reportItem, reportIndex) in reportList">
              <div class="line" :key="reportIndex">
                <span>{{ reportItem.name }}</span>
                <span class="leftBtn">
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-zoom-in"
                    @click="preFile(reportItem)"
                    title="预览"
                  ></el-button>
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-download"
                    @click="downloadFile(reportItem)"
                    title="下载"
                  ></el-button>
                </span>
              </div>
            </template>
          </div>
        </el-collapse-item>
        <el-collapse-item name="8" v-if="showAccept">
          <template slot="title">验收信息</template>
          <acceptance
            ref="acceptance"
            :formData="formData"
            @changeData="changeData"
            :orderType="menuType"
            :pageType="pageType"
          />
        </el-collapse-item>
        <el-collapse-item name="8" v-if="showApproval">
          <template slot="title">审批信息</template>
          <editForm
            :formConfig="approvalConfig"
            :formData="reviewData"
          ></editForm>
          <workFlow
            ref="workFlow"
            v-if="formData.id && showApproval"
            :isDetails="pageType == 'query'"
            :currentFlowData="formData"
            @submitSuccess="workFlowSuccess"
          ></workFlow>
        </el-collapse-item>
      </el-collapse>

      <template slot="boxContent">
        <checkRecord
          v-if="showCheckRecord"
          :orderData="formData"
          ref="checkRecord"
        ></checkRecord>
      </template>
    </editPageNew>
    <dialogPublic
      :title="'审核信息'"
      :show.sync="showFlowDialog"
      noFootBtn
      appendTobody
      fullscreen
      @doClose="() => (showFlowDialog = false)"
    >
      <workFlow
        v-if="showFlowDialog"
        :isDetails="pageType == 'query'"
        :currentFlowData="formData"
        workflowCode="experiment_wait_review"
        @submitSuccess="workFlowSuccess"
      ></workFlow>
    </dialogPublic>
    <dialogPublic
      :title="'转派工单'"
      :show.sync="showRedeploy"
      @doClose="() => (showRedeploy = false)"
      @doSubmit="toRedeploy"
      appendTobody
    >
      <div class="h100">
        <editForm
          v-if="showRedeploy"
          :formConfig="redeployConfig"
          ref="redeployForm"
          :formData="redeployData"
        />
      </div>
    </dialogPublic>
  </div>
</template>
<script>
/* 正常维护 */
import {
  saveOrUpdate, //保存正常维护工单
  submitApi, //提交正常维护工单
  deleteApi, //删除工单
  getDetailsApi, //获取正常维护工单详情
  getDispatchApi, //获取正常维护-派工信息
  saveDispatchApi, //保存正常维护-派工信息
  invalidApi,
} from "@/api/orderManagement/normalMaintenance";

/* 试验工单 */
import {
  getDetailsApi as getExperimentDetailsApi, //获取详情
  saveOrUpdate as saveOrUpdateExperiment, //保存工单
  submitApi as submitExperimentApi, //提交工单（修改状态）
  deleteApi as deleteExperimentApi, //删除工单
  getReviewInfoApi,
  submitExecutionApi, //执行中状态提交
  reportListApi, //根据工单Id查询工单下已经签名完成的附件列表
} from "@/api/orderManagement/experimentOrder";
/* 计划检修 */
import {
  getDetailsApi as getRepairDetailsApi, //获取详情
  saveOrUpdate as saveOrUpdateRepairnt, //保存工单
  submitApi as submitRepairntApi, //提交工单（修改状态）
  deleteApi as deleteRepairntApi, //删除工单
} from "@/api/orderManagement/planRepair";

import {
  getOrderDictionApi, //权限
  queryTicketListApi, //根据工单id查询关联的工作票列表
  queryTicketByOrderId, //根据工单id查询关联的工作票
} from "@/api/orderManagement/common";
import {
  getSubmitUserApi, //查询可提交的人员列表
} from "@/api/orderManagement/common";
import {
  getDetailsApi as overhaulDetails, //获取大修工单详情
} from "@/api/orderManagement/overhaul";
import workList from "./workList";
import checkRecord from "../checkRecord";
import workListExecute from "./workListExecute";
import addPerformItem from "@/views/orderManagement/publicModule/addItem";
import acceptance from "@/views/orderManagement/publicModule/acceptance";
import dispatch from "@/views/orderManagement/publicModule/dispatch";
import detailForm from "./detailForm";
import wokTicketList from "../wokTicketList";
import serviceList from "../serviceList";
import { redeployApi } from "@/api/orderManagement/defectOrder";
import { sendMessageToQywx } from "@/api/common.js"
export default {
  components: {
    workList,
    workListExecute,
    addPerformItem,
    acceptance,
    dispatch,
    checkRecord,
    detailForm,
    wokTicketList, //关联的工作票列表
    serviceList,
  },
  data() {
    return {
      userInfo: this.$store.getters.userInfo,
      currentDept: {},
      currentContext: "",
      orderTitle: "",
      showInput: false,
      topTitlename: "",
      userInput: false,
      showMore: false,
      haveTicketData: true,
      haveServiceData: true,
      showCheckRecord: false,
      deptManageName: "",
      status: "",
      activeNames: ["1", "2", "3"], //
      editFormData: { status: "" },
      creatInfo: {},
      showFlowDialog: false,
      acceptanceUnfold: false,
      hideBtnNo: true,
      parameterList: [],
      filesList: [],
      reportList: [], //已签名的文件列表
      /* 工作班成员 */
      workerList: [],
      chooseData: [],
      reviewData: {}, //审批信息
      tempTableData: [], //临时设备参数表格数据
      moveData: {},
      deptOption: [],
      userOption: [],

      approvalConfig: {
        itemArr: [
          {
            label: "设备管理单位",
            prop: "deptManageName", //多选时，字段要为数组类型
            idsStr: "deptManage",
            type: "text", //类型
            methods: (obj) => {},
            disabled: true,
            span: 8,
          },
          {
            label: "计划起止时间",
            prop: "dispatchTime",
            type: "datetimerange",
            pickerOptions: {},
            methods: (obj) => {},
            span: 8,
            disabled: true,
          },
          {
            label: "工作内容",
            prop: "context",
            type: "textarea",
            maxlength: "100",
            disabled: true,
            span: 8,
            rows: 2,
          },
          {
            label: "试验情况",
            prop: "testCase",
            type: "textarea",
            maxlength: "100",
            disabled: true,
            span: 24,
            rows: 4,
          },
        ],
      },
      formData: {},
      btnJurisdiction: [],
      dispatchData: {},
      acceptData: {},
      orderStatus: [
        "DRAFT",
        "WAIT_DISPATCH",
        "WAIT_EXECUTE",
        "IN_EXECUTE",
        "WAIT_ACCEPT",
        "ARCHIVED",
      ],
      statusName: ["草稿", "待派工", "待执行", "执行中", "待验收", "已归档"],
      needStatus: "1",
      pageType: "",
      deptIds: [],
      showRedeploy: false,
      redeployConfig: {
        itemArr: [
          {
            type: "select",
            label: "缺陷专业",
            prop: "major",
            required: true,
            selectOption: this.$store.getters["dirtData"]("common_major"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "common_major",
                val
              );
            },
            span: 24,
          },
          {
            label: "责任人",
            prop: "workerName", //多选时，字段要为数组类型
            propArr: "workerArr",
            idsStr: "worker",
            orgStr: "workerType", //是否是外单位，人员类型
            orgNameStr: "workerDeptName",
            orgIdStr: "workerDept",
            multiple: false, //是否多选
            isOutOrg: 0, //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            methods: (obj) => {},
            required: true,
            span: 24,
          },
          {
            label: "转派原因",
            prop: "reason",
            type: "textarea",
            maxlength: "500",
            required: true,
            span: 24,
            rows: 6,
          },
        ],
      },
      redeployData: {},
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "保存",
          icon: "el-icon-check",
          hide: [
            "WAIT_EXECUTE",
            "IN_EXECUTE",
            "ARCHIVED",
            "WAIT_REVIEW",
            "DEPRECATED",
          ].includes(this.status),
          methods: () => {
            this.doSubmit("save");
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "save",
            this.$store.getters["isBtnAuth"]("save")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("save") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "save")
          ),
        },
        {
          text: "提交",
          icon: "el-icon-position",
          hide: [
            "WAIT_DISPATCH",
            "IN_EXECUTE",
            "WAIT_EXECUTE",
            "ARCHIVED",
            "WAIT_REVIEW",
            "DEPRECATED",
          ].includes(this.status),
          methods: () => {
            this.doSubmit("submit");
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "submit",
            this.$store.getters["isBtnAuth"]("submit")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("submit") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "submit")
          ),
        },
        {
          text: "派工",
          icon: "el-icon-position",
          hide: this.status != "WAIT_DISPATCH",
          methods: () => {
            this.doSubmit("submit");
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "dispatch",
            this.$store.getters["isBtnAuth"]("dispatch")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("dispatch") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "dispatch")
          ),
        },
        {
          text: "执行",
          icon: "el-icon-position",
          hide: !["WAIT_EXECUTE"].includes(this.status),
          methods: () => {
            this.perform("执行");
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "execute",
            this.$store.getters["isBtnAuth"]("execute")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("execute") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "execute")
          ),
        },
        {
          text: "完成待验收",
          icon: "el-icon-position",
          hide: !["IN_EXECUTE"].includes(this.status),
          methods: () => {
            this.perform("完成待验收");
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "finishWaitAccept",
            this.$store.getters["isBtnAuth"]("finishWaitAccept")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("finishWaitAccept") &&
            this.$utils.getJurisdiction(
              this.btnJurisdiction,
              "finishWaitAccept"
            )
          ),
        },
        {
          text: "删除",
          icon: "el-icon-delete",
          hide: this.status != "DRAFT",
          methods: () => {
            this.deleteData();
          },
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "delete",
            this.$store.getters["isBtnAuth"]("delete")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("delete") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "delete")
          ),
        },
      ];
      return arr;
    },
    stepConfig() {
      let obj = {};
      let step = 0;
      if (this.status == "DEPRECATED") {
        obj = {
          nowStep: 0, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
          stepItem: ["已作废"],
        };
      } else {
        step = this.orderStatus.indexOf(this.status);
        obj = {
          nowStep: parseInt(step), //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
          stepItem: this.statusName,
        };
      }
      return obj;
    },
    moreBtnArr() {
      let arr = [
        {
          text: "办理工作票",
          methods: (item) => {
            this.selectTicketType(item);
          },
          hide: !["WAIT_EXECUTE", "IN_EXECUTE"].includes(this.status),
          isDictionary: true, //是否是数据字典
          child: this.$store.getters["dirtData"]("ticket_work_type"),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "handleTicketWork",
            this.$store.getters["isBtnAuth"]("handleTicketWork")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("handleTicketWork") &&
            this.$utils.getJurisdiction(
              this.btnJurisdiction,
              "handleTicketWork"
            )
          ),
        },
        {
          text: "检修申请",
          methods: (val) => {
            if (!val) {
              this.toService();
            }
          },
          hide: !["WAIT_EXECUTE", "IN_EXECUTE"].includes(this.status),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "application",
            this.$store.getters["isBtnAuth"]("application")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("application") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "application")
          ),
        },
        {
          text: "转派工单",
          methods: (val) => {
            if (!val) {
              this.showRedeploy = true;
            }
          },
          hide: !["WAIT_DISPATCH", "WAIT_EXECUTE", "IN_EXECUTE"].includes(
            this.status
          ),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "changeDispatch",
            this.$store.getters["isBtnAuth"]("changeDispatch")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("changeDispatch") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "changeDispatch")
          ),
        },
        {
          text: "工单变更",
          methods: (val) => {
            if (!val) {
              this.toChange();
            }
          },
          hide: !["WAIT_EXECUTE"].includes(this.status),
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "orderChange",
            this.$store.getters["isBtnAuth"]("orderChange")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("orderChange") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "orderChange")
          ),
        },
        {
          text: "让步接收",
          methods: (val) => {
            if (!val) {
              let { id, status, code } = this.formData;
              let routerForm = {
                orderId: id,
                pageType: "orderAdd",
              };
              this.goToDetails("concessionAcceptDetails", routerForm);
            }
          },
          hide: this.status != "IN_EXECUTE",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "concession",
            this.$store.getters["isBtnAuth"]("concession")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("concession") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "concession")
          ),
        },
        {
          text: "重大问题上报",
          methods: (val) => {
            if (!val) {
              let { id, status, code } = this.formData;
              let routerForm = {
                orderId: id,
                pageType: "orderAdd",
              };
              this.goToDetails("majorIssuesDetails", routerForm);
            }
          },
          hide: this.status != "IN_EXECUTE",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "question",
            this.$store.getters["isBtnAuth"]("question")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("question") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "question")
          ),
        },
        {
          text: "作废",
          methods: (val) => {
            if (!val) {
              this.toInvalid();
            }
          },
          hide:
            !["WAIT_DISPATCH", "WAIT_EXECUTE"].includes(this.status) ||
            this.menuType != "maintain",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "invalid",
            this.$store.getters["isBtnAuth"]("invalid")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("invalid") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "invalid")
          ),
        },
        {
          text: "工单抽查",
          methods: () => {
            this.$refs.editPage.showEditPageBox();
            this.showCheckRecord = true;
          },
          hide: this.status != "ARCHIVED",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "spotCheck",
            this.$store.getters["isBtnAuth"]("spotCheck")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("spotCheck") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "spotCheck")
          ),
        },
        {
          text: "复用工单",
          methods: () => {
            this.copyOrder();
          },
          hide: this.status == "" || this.menuType != "maintain",
          content: "",
          disabled: false,
        },
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
          hide: this.status == "",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "operateRecord",
            this.$store.getters["isBtnAuth"]("operateRecord")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("operateRecord") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "operateRecord")
          ),
        },
        {
          text: "打印",
          methods: () => {
            this.toPrint();
          },
          hide: this.status == "",
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "print",
            this.$store.getters["isBtnAuth"]("print")
          ),
          disabled: !(
            this.$store.getters["isBtnAuth"]("print") &&
            this.$utils.getJurisdiction(this.btnJurisdiction, "print")
          ),
        },
      ];
      return arr;
    },
    menuType() {
      let { menuType } = this.$route.meta;
      return menuType || "";
    },
    defaultTitle() {
      let deptManageName = this.deptManageName || "";
      let currentContext = this.currentContext || "";
      return deptManageName + currentContext;
    },
    baseAttachBtn() {
      if (
        ["DRAFT", undefined, null, ""].includes(this.status) &&
        ["edit", "add"].includes(this.pageType)
      ) {
        return false;
      } else {
        return true;
      }
    },
    editWorkList() {
      let status = this.status;
      return ["IN_EXECUTE"].includes(status) && this.pageType == "edit";
    },
    showWorkList() {
      let status = this.status;
      if (
        this.needStatus == "1" &&
        ["", "DRAFT", "WAIT_DISPATCH"].includes(status)
      ) {
        return true;
      } else {
        return false;
      }
    },
    showReport() {
      return (
        this.showPerform &&
        this.menuType == "experiment" &&
        this.reportList.length > 0
      );
    },
    showWorkListNext() {
      let status = this.status;
      if (
        this.needStatus == "1" &&
        [
          "WAIT_EXECUTE",
          "IN_EXECUTE",
          "WAIT_ACCEPT",
          "ARCHIVED",
          "WAIT_REVIEW",
        ].includes(status)
      ) {
        return true;
      } else {
        return false;
      }
    },
    showDispatch() {
      let status = this.status;
      //派工信息
      return (
        [
          "WAIT_DISPATCH",
          "WAIT_EXECUTE",
          "IN_EXECUTE",
          "ARCHIVED",
          "WAIT_ACCEPT",
          "WAIT_REVIEW",
        ].includes(this.status) && this.pageType != "add"
      );
    },
    showPerform() {
      //执行信息
      return (
        ["IN_EXECUTE", "ARCHIVED", "WAIT_ACCEPT", "WAIT_REVIEW"].includes(
          this.status
        ) && this.pageType != "add"
      );
    },
    showWorkTicket() {
      //执行信息
      return (
        [
          "WAIT_EXECUTE",
          "IN_EXECUTE",
          "ARCHIVED",
          "WAIT_ACCEPT",
          "WAIT_REVIEW",
          "DEPRECATED",
        ].includes(this.status) && this.pageType != "add"
      );
    },
    hidePerformBtn() {
      if (this.status == "IN_EXECUTE" && this.pageType == "edit") {
        return false;
      } else {
        return true;
      }
    },
    showAccept() {
      //验收信息
      return (
        ["ARCHIVED", "WAIT_ACCEPT"].includes(this.status) &&
        this.menuType != "experiment"
      );
    },
    showApproval() {
      //审批信息
      return (
        ["ARCHIVED", "WAIT_REVIEW"].includes(this.status) &&
        this.menuType == "experiment"
      );
    },
  },
  watch: {
    activeNames: {
      handler(val) {
        let item = val[val.length - 1];
        if (item == "1") {
          let name = this.formData.context || "";
          //草稿
          if (this.pageType != "add" && name == "") {
            this.$refs.basicForm.getDetails();
          }
        }
        if (item == "8") {
          this.acceptanceUnfold = !this.acceptanceUnfold;
        }
      },
      deep: true,
    },
    status: {
      handler(val) {
        this.formData.status = val || "";
        this.editFormData.status = val;
        this.unfoldMethod();
        //获取权限
        if (["maintain", "experiment", "repair"].includes(this.menuType)) {
          this.jurisdiction();
        }

        if (["WAIT_EXECUTE", "IN_EXECUTE"].includes(val)) {
          this.getSubmitUser();
        }
        if (val == "") {
          this.showMore = false;
        } else {
          this.showMore = true;
        }
      },
    },
    defaultTitle: {
      handler(val) {
        if (!this.userInput) {
          this.orderTitle = val;
        }
      },
    },
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let { id, pageType, orderId } = this.$route.query;
      this.pageType = pageType;
      if (id) {
        this.formData.id = id;
        //判断页面类型
        let haveJurisdiction = this.$store.getters["isBtnAuth"]("edit");
        this.pageType = haveJurisdiction ? "edit" : "detail";
      }
      if (this.menuType == "maintain") {
        this.topTitlename = "正常维护工单";
        if (orderId) {
          this.$refs.basicForm.getOrderDetails(orderId);
        }
      } else if (this.menuType == "experiment") {
        this.topTitlename = "试验工单";
        this.orderStatus = [
          "DRAFT",
          "WAIT_DISPATCH",
          "WAIT_EXECUTE",
          "IN_EXECUTE",
          "WAIT_REVIEW",
          "ARCHIVED",
        ];
        this.statusName = [
          "草稿",
          "待派工",
          "待执行",
          "执行中",
          "待审核",
          "已归档",
        ];
      } else if (this.menuType == "repair") {
        this.topTitlename = "计划检修工单";
      }
      this.initPage(); //去掉则新建无法初始化数据
    },
    initPage() {
      if (!["add", "orderAdd"].includes(this.pageType)) {
        this.showInput = false;
        this.formData.id = this.formData.id
          ? this.formData.id
          : this.$route.query.id;
        let name = this.formData.context || "";
        if (this.$refs.basicForm) {
          this.$refs.basicForm.getDetails(this.formData.id);
        }
      } else {
        //新增
        this.showInput = true;
        this.activeNames = ["1", "2"];
      }
    },
    //设置设备管理单位
    setDeptIds(data) {
      this.deptIds = data;
    },
    //获取页面权限
    jurisdiction() {
      let form = {
        orderId: this.formData.id,
        orderStatus: this.status,
        orderType: this.menuType,
      };
      getOrderDictionApi(form).then((res) => {
        let data = res.data;
        if (Array.isArray(data)) {
          this.btnJurisdiction = data;
        } else {
          this.btnJurisdiction = [];
        }
        this.changePageType();
      });
    },
    /* 结合角色权限，对页面是否可编辑进行控制 */
    changePageType() {
      let status = this.status || "";
      //用户角色权限
      let userJurisdiction = this.$store.getters["isBtnAuth"]("edit");
      //业务控制权限
      let businessJurisdiction = this.$utils.getJurisdiction(
        this.btnJurisdiction,
        "save"
      );
      let haveJurisdiction = userJurisdiction && businessJurisdiction;
      //确定pageType类型
      this.pageType = haveJurisdiction ? "edit" : "detail";
    },

    //折叠与展开
    unfoldMethod() {
      let status = this.status;
      if (["DRAFT", "DEPRECATED"].includes(status)) {
        //草稿
        this.activeNames = ["1", "2"];
      } else if (["WAIT_DISPATCH"].includes(status)) {
        //待派工
        this.activeNames = ["3"];
      } else if (status == "WAIT_EXECUTE") {
        this.activeNames = ["1", "4", "5", "6"];
      } else if (["IN_EXECUTE"].includes(status)) {
        //执行中
        this.activeNames = ["4", "5", "6", "7"];
      } else if (["WAIT_REVIEW", "WAIT_ACCEPT"].includes(status)) {
        //试验工单待审核、正常维护工单验收
        this.activeNames = ["8"];
        if (this.menuType == "experiment") {
          this.getReviewInfo();
        }
      } else if (status == "ARCHIVED") {
        //已归档
        this.activeNames = [];
        if (this.menuType == "experiment") {
          this.getReviewInfo();
        }
      }
      if (
        ["IN_EXECUTE", "WAIT_REVIEW", "ARCHIVED"].includes(status) &&
        this.menuType == "experiment"
      ) {
        this.getFileList(); //获取试验报告列表
      }
    },
    getReviewInfo() {
      getReviewInfoApi(this.formData.id).then((res) => {
        let data = res.data || {};
        data.dispatchTime = [data.startTime, data.endTime];
        let voList = data.equipmentConclusionVoList || [];
        //试验情况
        let testCase = "";
        voList.map((i) => {
          let statusName = "";
          if (i.passStatus == "1") {
            statusName = "合格";
          } else if (i.passStatus == "0") {
            statusName = "不合格";
          } else {
            statusName = i.passStatus;
          }
          testCase = testCase + i.equipmentName + "：" + statusName + "\n";
        });
        data.testCase = testCase;
        this.reviewData = data;
      });
    },
    //获取可提交的人员数组
    getSubmitUser() {
      getSubmitUserApi(this.formData.id).then((res) => {
        this.submitUser = res.data || [];
      });
    },
    async doSubmit(type) {
      let status = this.formData.status || "";
      let data = {};
      //基本信息的保存
      if (
        status == "DRAFT" ||
        (["add", "orderAdd"].includes(this.pageType) && status == "")
      ) {
        //新增或者草稿状态时，保存正常维护-基本信息，提交-基本信息
        let isSubmit = false;
        if (type == "submit") {
          data = await this.$refs.basicForm.getFormData();
        } else {
          //保存时不做校验
          data = await this.$refs.basicForm.getFormData(false);
        }
        data.title = this.orderTitle;
        //是否需要作业表单
        if (data.needStatus == "1") {
          let workListData = await this.$refs.workList.getWorkListData();
          let workProcessData = await this.$refs.workList.getworkProcessData();
          if (this.menuType == "experiment") {
            /* 试验工单 */
            data.experimentEquipmentPoList = workProcessData; //作业过程
            data.experimentReadyPoList = workListData; //作业准备getBookListData
          } else if (this.menuType == "maintain") {
            /* 正常维护单 */
            data.maintainEquipmentPoList = workProcessData; //作业过程
            data.maintainReadyPoList = workListData; //作业准备getBookListData
          } else if (this.menuType == "repair") {
            /* 计划检修 */
            data.repairEquipmentPoList = workProcessData; //作业过程
            data.repairReadyPoList = workListData; //作业准备getBookListData
          }
          data.orderInstructionBeanList = this.$refs.workList.getBookListData();
          if (workProcessData.length > 0) {
            isSubmit = true;
          }
        } else {
          data.orderEquipPoList = this.$refs.basicForm.getEquipList();
          isSubmit = true;
        }
        data.title = this.orderTitle;
        if (data.dispatchTime) {
          data.startTime = data.dispatchTime[0];
          data.endTime = data.dispatchTime[1];
        }
        data.orderLocationList = this.$refs.basicForm.getLocationList();
        delete data.dispatchTime;
        delete data.deptManageArr;
        delete data.location;
        delete data.locationArr;
        delete data.locationName;
        if (type == "save") {
          data.isCommit = false;
          isSubmit = true;
        } else if (type == "submit") {
          data.isCommit = true;
        }
        if (isSubmit) {
          var actionApi = null;
          let orderName = "";
          if (this.menuType == "maintain") {
            /* 正常维护单 */
            actionApi = saveOrUpdate;
            orderName = "正常维护工单";
          } else if (this.menuType == "experiment") {
            /* 试验工单 */
            actionApi = saveOrUpdateExperiment;
            orderName = "试验工单";
          } else if (this.menuType == "repair") {
            /* 计划检修 */
            actionApi = saveOrUpdateRepairnt;
            orderName = "计划检修";
          }
          actionApi(data).then(async (res) => {
            this.$utils.updateStorage();
            this.$message.success("操作成功！");
            await this.$refs.basicForm.setAttachId(res.data, this.pageType);
            if (["add", "orderAdd"].includes(this.pageType)) {
              this.pageType = "edit";
              this.formData.id = res.data;
              if (type == "submit") {
                this.$utils.addOperateLog(
                  this.formData.id,
                  `新增并提交-${orderName}`
                );
              } else {
                this.$utils.addOperateLog(
                  this.formData.id,
                  `新增-${orderName}`
                );
              }
              this.changeRouter(type);
            } else if (status == "DRAFT" && type == "submit") {
              this.$utils.addOperateLog(
                this.formData.id,
                `修改并提交-${orderName}`
              );
              this.changeData(res.data);
            } else {
              this.$utils.addOperateLog(this.formData.id, `修改-${orderName}`);
              this.changeData(res.data);
            }
          });
        } else {
          this.$message.warning("请填写作业表单");
        }
      } else if (status == "WAIT_DISPATCH") {
        //待派工状态时，保存-派工信息，提交-派工信息
        this.$refs.dispatch.saveData(type);
      } else if (status == "WAIT_ACCEPT") {
        //验收状态时，保存-验收信息，提交-验收信息
        this.$refs.acceptance.saveData(type);
      }
    },
    //转派工单
    async toRedeploy() {
      this.showRedeploy = false;
      let data = await this.$refs.redeployForm.getFormData();
      if (this.status == "WAIT_DISPATCH") {
        data.dispatch = false;
      } else {
        data.dispatch = true;
      }
      data.preMajor = this.formData.major;
      data.orderId = this.formData.id;
      data.orderType = this.menuType;
      data.workerType = this.$utils.changeUserType(data.workerType);
      redeployApi(data).then((res) => {
        this.$message.success("操作成功");
        this.$utils.addOperateLog(
          this.formData.id,
          `转派给:${data.workerDeptName} ${data.workerName}`
        );
        this.$refs.basicForm.getDetails(this.formData.id);
        if (this.status == "WAIT_DISPATCH") {
          setTimeout(() => {
            this.jurisdiction();
          }, 200);
        }
      });
    },
    changeRouter(type) {
      /* 修改路由参数 */
      let obj = JSON.parse(JSON.stringify(this.$router.currentRoute.query));
      delete obj.orderId;
      obj = Object.assign(obj, {
        id: this.formData.id,
        pageType: "edit",
        status: type == "submit" ? "WAIT_DISPATCH" : "DRAFT",
      });
      this.$router.push({
        query: obj,
      });
    },

    //执行
    async perform(operationName) {
      let status = this.formData.status || "";
      let account = this.userInfo.id;
      let form = {};
      let completeObj = {};
      //验证是否可以提交
      let canSubmit = true;
      /* 判断当前登录人是否有权限提交 */
      // if (!["maintain", "experiment"].includes(this.menuType)) {
      //   //正常维护工单已做业务权限控制，所以不需要这里的判断了
      //   if (this.submitUser.includes(account)) {
      //     let index = this.orderStatus.indexOf(this.status);
      //     form = {
      //       status: this.orderStatus[index + 1],
      //     };
      //   } else {
      //     canSubmit = false;
      //     this.$message.warning("只有工作负责人或者工作班成员才能执行！");
      //   }
      // } else {
      let index = this.orderStatus.indexOf(this.status);
      form = {
        status: this.orderStatus[index + 1],
      };
      //}
      if (canSubmit) {
        /* 执行中提交(有作业表单时)-判断作业表单是否填写完整 */
        if (status == "IN_EXECUTE" && this.formData.needStatus == 1) {
          completeObj = await this.$refs.workListExecute.judgeComplete();
          canSubmit = completeObj.isComplete;
          if (canSubmit == false) {
            this.$message.warning(completeObj.message);
          }
        }
      }
      //验证执行信息是否填写完成
      if (canSubmit && status == "IN_EXECUTE") {
        canSubmit = await this.$refs.perform.isComplete();
        if (!canSubmit) {
          this.$message.warning("请填写执行信息！");
        }
      }
      if (canSubmit) {
        let message = "";
        let res = await queryTicketByOrderId(this.formData.id);
        let workStatus = res.data || [];
        if (workStatus.length > 0) {
          //有关联工作票
          let arr = [];
          if (status == "WAIT_EXECUTE") {
            arr = [1, 2, 3, 4, 5];
          } else {
            arr = [1, 2, 3, 4, 5, 6, 7];
          }
          //取交集
          let intersection = workStatus.filter((val) => {
            return arr.indexOf(val) > -1;
          });
          if (intersection.length > 0) {
            //有交集
            if (status == "IN_EXECUTE") {
              message = "未归档";
            } else {
              message = "未许可";
            }
          }
          if (message) {
            this.$confirm(`当前存在${message}的工作票，是否继续?`, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.performOrder(form, status, operationName);
              })
              .catch((e) => {});
          } else {
            this.performOrder(form, status, operationName);
          }
        } else {
          //没有关联工作票
          this.performOrder(form, status, operationName);
        }
      }
    },
    performOrder(form, status, operationName) {
      var actionApi = null;
      let orderName = "";
      if (this.menuType == "experiment" && status == "IN_EXECUTE") {
        this.showFlowDialog = true;
      } else {
        if (this.menuType == "maintain") {
          /* 正常维护单 */
          form.maintainId = this.formData.id;
          actionApi = submitApi;
          orderName = "正常维护工单";
        } else if (this.menuType == "experiment") {
          /* 试验工单 */
          form.orderId = this.formData.id;
          actionApi = submitExperimentApi;
          orderName = "试验工单";
        } else if (this.menuType == "repair") {
          /* 计划检修 */
          form.repairId = this.formData.id;
          actionApi = submitRepairntApi;
          orderName = "计划检修";
        }

        this.$refs.dispatch.getDispatchData().then(resp => {
          let sendMessageParam = {}
          if(operationName === '执行') {
          sendMessageParam = {
            title: this.formData.title,
            handler: resp.worker || resp.trackPersonId
            }
          }
          if(operationName === '完成待验收') {
            sendMessageParam = {
              title: this.formData.title,
              handler: this.formData.createBy
            }
          }
          // 发送消息
          sendMessageToQywx(sendMessageParam).then(() => {
            actionApi(form).then((res) => {
              this.$utils.updateStorage();
              this.$message.success("操作成功");
              this.$utils.addOperateLog(
                this.formData.id,
                `${operationName}-${orderName}`
              );
              this.changeData();
            });
          })
        })
      }
    },
    //改变数据状态
    changeData(id) {
      this.$refs.basicForm.getDetails(id); //获取详情
    },
    //保存附件
    saveAttachFile() {
      this.$refs.attachForm.save();
    },
    //删除
    deleteData() {
      let { status, sourceId } = this.formData;
      //对数据来源进行判断（待完善）
      if (["DRAFT"].includes(status) && sourceId == "enter_order") {
        this.$confirm(`是否确认删除`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            var actionApi = null;
            if (this.menuType == "maintain") {
              /* 正常维护单 */
              actionApi = deleteApi;
            } else if (this.menuType == "experiment") {
              /* 试验工单 */
              actionApi = deleteExperimentApi;
            } else if (this.menuType == "repair") {
              /* 计划检修 */
              actionApi = deleteRepairntApi;
            }
            actionApi(this.formData.id).then((res) => {
              this.$utils.updateStorage();
              this.$message.success("操作成功");
              this.$refs.editPage.closePage();
              this.updateData();
            });
          })
          .catch((e) => {});
      } else {
        this.$message.warning("只能删除手工录入的数据！");
      }
    },
    //根据是否是外单位改变界面显示
    changeConfig(obj) {
      let itemArr = this.dispatchConfig.itemArr;
      for (let i in itemArr) {
        if (itemArr[i].prop == "trackPerson") {
          if (obj.value == 1) {
            //外单位
            itemArr[i].isHide = false;
          } else {
            itemArr[i].isHide = true;
          }
        }
        //设置选人以及选单位的组件是本单位还是外单位
        if (
          itemArr[i].prop == "headName" ||
          itemArr[i].prop == "deptWorkName"
        ) {
          //负责人
          itemArr[i].isOutOrg = obj.value;
        }
      }
    },
    //工作流提交成功之后
    workFlowSuccess() {
      this.showFlowDialog = false;
      if (this.$refs.workFlow) {
        this.$refs.workFlow.getFlowInfo();
      }
      this.$utils.updateStorage();
      this.$refs.basicForm.getDetails();
    },
    //更新基本信息
    changeFormData(val) {
      this.formData = val;
      this.status = val.status || "";
    },
    //初始化用户是否自输入了标题
    initUserInput(val) {
      this.userInput = val;
    },
    //用户没有自己输入标题的情况下，根据标题规则自动更新标题
    setOrderTitle(data) {
      if (!this.userInput) {
        this.orderTitle = data;
      }
    },
    //失去焦点
    loseFocus() {
      if (
        ["", null].includes(this.orderTitle) ||
        this.orderTitle.match(/^[ ]*$/)
      ) {
        if (this.$refs.basicForm.getTitle()) {
          this.$message.warning("标题不能为空，已为您自动生成标题！");
          this.orderTitle = this.$refs.basicForm.getTitle();
          this.showInput = false;
        } else {
          this.showInput = true;
        }
      } else {
        this.showInput = false;
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    setNeedStatus(val) {
      this.needStatus = val;
    },

    setDispatchTime(obj) {
      this.formData = Object.assign(this.formData, obj);
    },
    //用户输入工单标题
    userInputTitle(val) {
      if (["", null].includes(val) || val.match(/^[ ]*$/)) {
        this.userInput = false;
      } else {
        this.userInput = true;
      }
    },
    getFileList() {
      reportListApi(this.formData.id).then((res) => {
        this.reportList = res.data || [];
      });
    },

    //预览指导书
    preFile(item) {
      window.open(
        process.env.VUE_APP_BASEURL +
          "/eam-common-web/attachment/preview/?fileId=" +
          item.id
      );
      return true;
    },
    //下载指导书
    downloadFile(item) {
      this.$utils.downloadFile(item.id, item.name, item.path);
    },
    //打印预览
    toPrint() {
      window.print();
    },
    //选择工作票类型
    selectTicketType(item) {
      let { id, code } = this.formData;
      let data = { orderId: id, orderCode: code, orderType: this.menuType };
      let routerForm = {
        val: JSON.stringify(data) || "",
        pageType: "orderAdd",
        ticketType: item.value,
      };
      this.goToDetails("workTicketProcessingDetails", routerForm);
    },
    goToDetails(name, queryData) {
      const { href } = this.$router.resolve({
        name: name,
        query: queryData,
      });
      window.open(href, "_blank");
    },
    //检修申请
    toService() {
      let { id, code } = this.formData;
      let query = {
        id: "",
        pageType: "orderAdd",
        orderId: id,
        orderCode: code,
      };
      this.goToDetails("overhaulApplicationDetails", query);
    },
    //作废
    toInvalid() {
      invalidApi(this.formData.id).then((res) => {
        this.$utils.addOperateLog(this.formData.id, `作废了此工单`);
        this.$utils.updateStorage();
        this.$message.success("操作成功！");
        this.changeData(res.data);
      });
    },
    toChange() {
      let { id, code } = this.formData;
      let form = {
        pageType: "orderAddChange",
        orderId: id,
        orderCode: code,
        orderType: this.menuType,
      };
      let { href } = this.$router.resolve({
        name: "orderChangeDetails",
        query: form,
      });
      window.open(href, "_blank");
    },

    //工单抽查
    closeCheckRecord() {
      this.showCheckRecord = false;
    },
    copyOrder() {
      let form = {
        pageType: "add",
        orderId: this.formData.id,
      };
      let { href } = this.$router.resolve({
        path: "/orderManagement/normalMaintenance/details",
        query: form,
      });
      window.open(href, "_blank");
    },
  },
};
</script>
<style lang="less" scoped>
.normalDetails {
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .titleText {
    display: inline-block;
    height: 30px;
    max-width: 800px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-right: 5px;
  }
  .el-link {
    margin-bottom: 5px;
  }
  .attachConten {
    display: flex;
    flex-flow: wrap nowrap;
    .redPoint {
      color: red;
    }
    .attachTitle {
      width: 120px;
    }
    .tebleDiv {
      width: 100%;
    }
  }
  .orderTitle {
    height: 60px;
    margin: 0 0 10px 0;
    .tipText {
      color: #cecece;
      text-align: left;
    }
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 600px;
      height: 40px;
      line-height: 40px;
    }
    .remindColor {
      /deep/.el-input__inner {
        border: 1px solid red !important;
      }
    }
  }
  .reportDiv {
    width: 500px;
    .line {
      padding: 0px 15px;
      border-radius: 3px;
      display: flex;
      flex-flow: wrap nowrap;
      justify-content: space-between;
    }
    .line:hover {
      background-color: #2a7af313;
    }
  }
}
</style>
